package de.homelabs.modules.tools.strategy;

import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;


/**
 * generic class that reads a xml from classpath an converts its content to an object structure<br />
 * <br />
 * @author D.Mueller
 *
 * @param <T> - Class of the xml root element
 */
public class HLJAXBImportStrategy<T> implements IHLImportStrategy<T>{

	//vars
	private Class registeredClass;

	private Class[] registeredClasses = null;
	
	/**
	 * default constructor
	 */
	public HLJAXBImportStrategy(){
	}
	
	/**
	 * parameter constructor
	 * @param registeredClass
	 */
	public HLJAXBImportStrategy(Class importClass){
		this.registeredClass = importClass;
	}

	/**
	 * imports an element list using jaxb strategy
	 * 
	 * @param String fileName
	 * @return T
	 */
	@SuppressWarnings("unchecked")
	public T importElementList(String fileName){
		JAXBContext context = createJAXBContext();
		Unmarshaller um;
		
		try {
			//get JAXBContext
			um = context.createUnmarshaller();
			//read xml 
			InputStream in = this.getClass().getResourceAsStream(fileName);
			//unmarshall
			return (T) um.unmarshal(in);
		} catch (JAXBException e) {
			//TODO: Logger
			System.out.println(e);
			return null;
		}
	}
	
	/****************
	 * functions	*
	 ****************/
	/**
	 * create JAXB context and register classes
	 * @return JAXBContext
	 */
	private JAXBContext createJAXBContext(){
		try {
			if (registeredClasses != null){
				return JAXBContext.newInstance(registeredClasses, null);
			} else {
				return JAXBContext.newInstance(registeredClass);
			}
		} catch (JAXBException e) {
			System.out.println(e);
			return null;
		}
	}

	public Class[] getRegisteredClasses() {
		return registeredClasses;
	}

	public void setRegisteredClasses(Class[] registeredClasses) {
		this.registeredClasses = registeredClasses;
	}
	
	
	/*******************
	 * getter / setter *
	 *******************/
//	public void setRegisteredClass(T registeredClass) {
//		this.registeredClass = registeredClass;
//	}
}
